import java.math.BigInteger
import kotlin.math.ceil
import kotlin.math.sqrt

/**
 *Create by Fanketly on 2022/9/5
 *Gitee:https://gitee.com/fanketly
 *desc:fold、reduce函数->归约操作;tailrec——》尾递归
 *
 */
fun sumByFold(intArray: IntArray) =
    intArray.fold(0) { acc: Int, i: Int ->
        acc + i
    }

fun sumByReduce(intArray: IntArray) =
    intArray.reduce { acc: Int, i: Int ->
        acc + i
    }

tailrec fun factorialByTailrec(n: Long, acc: BigInteger = BigInteger.ONE): BigInteger =
    when (n) {
        0L -> BigInteger.ONE
        1L -> acc
        else -> factorialByTailrec(n - 1, acc * BigInteger.valueOf(n))
    }

private fun Int.isPrime() =
    this == 2 || (2..ceil(sqrt(this.toDouble())).toInt()).none { divisor -> this % divisor == 0 }

fun nextPrime(num: Int) = generateSequence(num + 1) { it + 1 }.first(Int::isPrime)